package com.csx.governance.traffic.condition;

import cn.hutool.core.util.ObjectUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author cuisongxu
 * @date 2023/2/25 14:03
 */
public class ComponentFactory {

    private final Map<String, Component.Builder> builderMap;

    public ComponentFactory(List<Component.Builder> builders) {
        Map<String, Component.Builder> map = new HashMap<>();
        builders.forEach(builder -> builder.supportedConfigIds().forEach(configId -> map.put(configId, builder)));
        this.builderMap = map;
    }

    public Component build(String type, String... params) throws IllegalArgumentException{
        String configId = Component.Builder.getConfigId(type, params);
        Component.Builder builder = builderMap.get(configId);
        if(ObjectUtil.isEmpty(builder)) {
            throw new IllegalArgumentException("Illegal ComponentConfig");
        }
        return builder.build(type, params);
    }
}
